import {
  postApiRole as Create,
  putApiRoleById as Update
} from '@/services/furion-cms/role'
import {
  ModalForm,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea
} from '@ant-design/pro-form';
import React, { useRef } from 'react';

import type { ModalProps } from 'antd';
import type { ProFormInstance } from '@ant-design/pro-form';
import { message } from 'antd';
import { useIntl } from 'umi';

interface DetailProps {
  modalVisible?: boolean;
  recored?: API.RoleDetailDto;
  onUpdate?: () => void;
  onVisibleChange: (visit: boolean) => void;
  modalProps?: Omit<ModalProps, 'visible'>;
}

const DetailViewer: React.FC<DetailProps> = (props) => {
  const { modalVisible, onUpdate, onVisibleChange, modalProps, recored } = props;

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  // 绑定一个 ProFormInstance 实例
  const formRef = useRef<ProFormInstance<API.RoleCreateAndUpdateDto>>();

  const finishHandle = (values: API.RoleCreateAndUpdateDto) => {
    console.log('finishHandle', values);
    const successHandle = () => {
      message.success('角色信息保存成功');
      onUpdate?.();
      return true;
    }
    if (recored?.id) {
      return Update({ id: recored?.id }, { ...values })
        .then(successHandle);
    }
    else {
      return Create({ ...values })
        .then(successHandle);
    }
  }

  return (
    <ModalForm<API.RoleCreateAndUpdateDto>
      title={recored?.id ? intl.formatMessage({
        id: 'pages.role.detail.title.edit',
        defaultMessage: '编辑角色'
      }) : intl.formatMessage({
        id: 'pages.role.detail.title.create',
        defaultMessage: '创建角色'
      })}
      modalProps={{
        destroyOnClose: true,
        width: 500,
        maskClosable: false,
        ...modalProps
      }}
      visible={modalVisible}
      initialValues={recored}
      onFinish={finishHandle}
      formRef={formRef}
      onVisibleChange={onVisibleChange}
    >
      <ProFormText
        name="name"
        label={intl.formatMessage({
          id: 'pages.role.detail.input.name',
          defaultMessage: '角色名称'
        })}
        placeholder={intl.formatMessage({
          id: 'pages.role.detail.input.name.placeholder',
          defaultMessage: '请输入您要使用的角色名称'
        })}
        rules={[
          {
            required: true, message: intl.formatMessage({
              id: 'pages.role.detail.input.name.rules',
              defaultMessage: '角色名称必填'
            })
          },
        ]}
        required />
      <ProFormTextArea
        name="description"
        label={intl.formatMessage({
          id: 'pages.role.detail.input.description',
          defaultMessage: '描述'
        })} />
      <ProFormSwitch
        name="isDefault"
        label={intl.formatMessage({
          id: 'pages.role.detail.input.isDefault',
          defaultMessage: '默认'
        })}
      />
    </ModalForm>
  )
}

export default DetailViewer
